package com.example.demo.service.impl;

/**
 * @author 高俊
 * @create 2021-08-2021/8/16-14:57
 */

import com.example.demo.config.GetHttpSessionConfigurator;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;


/**
 * @author zhengkai.blog.csdn.net
 */
@ServerEndpoint(value = "/myWs/{userId}",configurator = GetHttpSessionConfigurator.class)
@Service
public class MyWebSocket {

    private static Map<String, MyWebSocket> onlineUser = new HashMap<>();

    private Session session;

    private HttpSession httpSession;

    private static ConcurrentHashMap<String,MyWebSocket> webSocketMap = new ConcurrentHashMap<String,MyWebSocket>();


    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) {
        webSocketMap.forEach((k,v)->{
            try {
                v.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }

        });
    }
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    /**
     * 连接成功
     *
     * @param session
     */
    @OnOpen
    public void onOpen(@PathParam("userId")String userId, Session session) {
        System.out.println(userId);
        this.session = session;
        webSocketMap.put(userId, this);
        List list = new ArrayList();
        webSocketMap.forEach((k, v) -> list.add(k));
//        addOnlineCount();
        System.out.println("有新连接加入！当前在线人数为" + webSocketMap.size());
        sendInfo("当前共有" + webSocketMap.size() + " 位用户在线,userId是:" + list.toString());
    }
    /**
     * 连接关闭
     *
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }

    /**
     * 接收到消息
     *
     * @param text
     */
    @OnMessage
    public String onMsg(String text) throws IOException {
        return "servet 发送：" + text;
    }

}
